package com.demo02_interaction.task;

import com.demo02_interaction.client.VideoServiceClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@RequiredArgsConstructor
@Slf4j
public class LikeSyncTask {
    private final RedisTemplate<String, String> redisTemplate;
    private final VideoServiceClient videoServiceClient;

    @Scheduled(cron = "0 */5 * * * ?") // 每5分钟执行一次
    public void syncLikeCountToDB() {
        // 1. 扫描Redis中所有 count:video:* 的key
        Set<String> keys = redisTemplate.keys("count:video:*");
        if (keys == null || keys.isEmpty()) return;

        for (String countKey : keys) {
            try {
                // 2. 从key中解析出videoId
                Long videoId = Long.parseLong(countKey.split(":")[2]);
                // 3. 从Redis中获取likeCount
                Object likeCountObj = redisTemplate.opsForHash().get(countKey, "likeCount");
                if (likeCountObj != null) {
                    Long likeCount = Long.valueOf(likeCountObj.toString());
                    // 4. 通过Feign客户端调用视频服务来更新点赞数
                    videoServiceClient.updateLikeCount(videoId, likeCount.intValue());
                    
                    // 同步成功后，可以清空Redis中的计数，或者保留它用于下一次增量同步
                    redisTemplate.opsForHash().put(countKey, "likeCount", "0");
                }
            } catch (Exception e) {
                log.error("同步点赞数到视频服务失败: {}", countKey, e);
                // 处理异常，可以选择重试或记录日志
            }
        }
    }
}
